// index.js
const express = require('express');
const { Readable } = require('stream');

const app = express();
const PORT = 3000;

// 创建一个可读流
const createStream = () => {
    const readable = new Readable({
        read() { }
    });

    // 模拟数据的生成
    let count = 0;
    const intervalId = setInterval(() => {
        if (count < 10) { // 发送10条数据
            readable.push(`这是第 ${count + 1} 条数据\n`);
            count++;
        } else {
            clearInterval(intervalId);
            readable.push(null); // 表示数据流结束
        }
    }, 500); // 每隔1秒发送一条数据

    return readable;
};

const markdownText = `
# Hello, Markdown!Hello, Markdown!Hello, Markdown!Hello, Markdown!Hello, Markdown!Hello, Markdown!Hello, Markdown!


![图片1](https://psy-public.obs.myhuaweicloud.com/bpai/static/knowledge-demo/image003.jpg)![图片1](https://psy-public.obs.myhuaweicloud.com/bpai/static/knowledge-demo/image003.jpg)
<img src="https://psy-public.obs.myhuaweicloud.com/bpai/static/knowledge-demo/image037.jpg"  />&nbsp;&nbsp;&nbsp;
<img src="https://psy-public.obs.myhuaweicloud.com/bpai/static/knowledge-demo/image004.jpg"   />

[批量上传模版](https://psy-public.obs.myhuaweicloud.com/bpai/static/knowledge-demo/批量上传模版1.xlsx)

<a href="https://psy-public.obs.myhuaweicloud.com/bpai/static/knowledge-demo/批量上传模版1.xlsx" target="_blank">
  <span style="color: blue; font-weight: bold;">批量上传模版</span>
</a>
`;
// 将字符串按段落分割
const paragraphs = markdownText.trim();


// 定义流式数据的路由
app.post('/stream', (req, res) => {
    //   res.setHeader('Content-Type', 'text/plain');
    //   const stream = createStream();
    //   stream.pipe(res); // 将可读流的内容通过管道传递给响应



    // 设置响应头
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    let index = 0;
    // 启动定时器，每 500 毫秒输出一个段落
    const intervalId = setInterval(() => {
        if (index < paragraphs.length) {
            console.log(`段落 ${index + 1}: ${paragraphs[index]}`);
            const data = {
                sessionId: null,
                chatNo: null,
                msgId: null,
                contextMsg: paragraphs[index] + (paragraphs[index + 1] || '') + (paragraphs[index + 2] || ''), // 这里您可以插入实际的数据
                source: null,
                recommend: null,
                rspCode: null
            };

            // 在这里构建 SSE 数据格式
            res.write(`data: ${JSON.stringify(data)}\n\n`);
            index += 3;
        } else {
            let done = ['DONE']
            const data = {
                sessionId: null,
                chatNo: null,
                msgId: null,
                contextMsg: paragraphs[index] + paragraphs[index + 1] + paragraphs[index + 2], // 这里您可以插入实际的数据
                source: null,
                recommend: [
                    { content: "建筑服务增值税简易计税方法是什么？", recommendNo: "676116500df461f7fc230e45" },
                    { content: "一般纳税人和小规模纳税人在建筑服务增值税上有什么区别？", recommendNo: "676116500df461f7fc230e46" },
                    { content: "最新的建筑服务增值税税率调整情况是怎样的？", recommendNo: "676116500df461f7fc230e47" }
                ],
                rspCode: null
            };
            // 在这里构建 SSE 数据格式
            res.write(`data: ${JSON.stringify(data)}\n\n`);
            res.write(`data:[DONE]\n\n`);
            clearInterval(intervalId); // 清除定时器
        }
    }, 50);

    // 当客户端断开连接时，清除定时器
    req.on('close', () => {
        clearInterval(intervalId);
        res.end(); // 结束响应
    });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`Server is running at http://localhost:${PORT}`);
});